﻿// next to do??
/*
那個最新回應實在是太難寫了
難寫到我這個最新文章居然只花兩天就寫好了
幾乎一樣的格式，但是簡單100倍，一天就搞定。
喜歡就拿去玩吧
自用就不用告訴我了
如果修改後發佈，請註明參考來源<--就是我
09/13/2007
*/
/*
tagListSetting.postShow: 每頁顯示文章數
tagListSetting.defaultPost: 預設標籤，預設為最新文章
tagListSetting.loadingImage: 載入時的文字與圖片
tagListSetting.headerButton: 是否顯示標籤按鈕
tagListSetting.tagsShow: 是否預設顯示標籤雲
tagListSetting.lineHeight: 設定標籤雲字間的高度，免得字大的時候疊在一起
*/
var tagListSetting = {
postShow:5 ,
labelName:'',
defaultPost: '',
loadingImage: '<img src="http://lvchen716.googlepages.com/2-0.gif"/>&nbsp;資料載入中...',
headerButton:true,
tagsShow: false,
lineHeight:24
};
var tagListinner = {
startIndex: 1,
originalTag:'',
blogName:''
};
var tagListFunction = {};

tagListFunction.addHeaderButton = function ()
{
	var categoryList = jQuery('#'+tagListSetting.labelName);
	var blockInfo = '<div id="headerBlock"><span class = "buttonStyle"><a href="javascript:if(tagListSetting.defaultPost!=&quot;&quot;) tagListFunction.nextPage(0,&quot;&quot;)">最新文章</a></span><span class="buttonStyle"><a href = "javascript:void(0)">選擇標籤</a></span></div>';
	if (!tagListSetting.tagsShow)
		categoryList.find('ul:eq(0)').hide().find('li').css({background:'none',lineHeight:tagListSetting.lineHeight+'px'});
	else
		categoryList.find('ul:eq(0) li').css({background:'none',lineHeight:tagListSetting.lineHeight+'px'});
	
	categoryList.find('.widget-content').prepend(blockInfo).end().find('.buttonStyle').css('marginLeft','1em').slice(1,2).click(function(){
		var listTableShow = jQuery(this).parent().next();
		if (listTableShow.is(':visible'))
			listTableShow.fadeOut();
		else
			listTableShow.fadeIn();
    });
};

tagListFunction.Util =function(json)
{
	var posts = json.feed.entry;
	var tagPostNum = json.feed.openSearch$totalResults.$t;
	var categoryList = jQuery('#'+tagListSetting.labelName);
	if (tagPostNum != 0)
	{
		var temp = '<ul>';
		if (tagListinner.startIndex+tagListSetting.postShow > tagPostNum)
			var looping = tagPostNum - tagListinner.startIndex+1;
		else
			var looping = tagListSetting.postShow;
		for (var i=0; i < looping ; i++) 
		{
			post = json.feed.entry[i];
			var title=post.title.$t;
			var link=post.link[0].href;
			// 未來應加入預視窗格
			var timestamp=post.published.$t.substr(0,10);
			temp += '<li><a href="'+ link +'">'+ title +'</a> '+ timestamp +'</li>';
		}
		temp+='</ul>';
		categoryList.find('#postsList').html(temp);
		// 老方法，加上頁尾
		function addFooterButton()
		{
			jQuery('#listLoading').remove();
			if (tagListSetting.defaultPost == '')
				var listInfo = '<div id="footerInfo">最新文章 ' + tagListinner.startIndex +'~'+ (tagListinner.startIndex+looping-1) +'，共有 '+ tagPostNum +' 篇文章';
			else
				var listInfo = '<div id="footerInfo">' + tagListSetting.defaultPost + '系列 ' + tagListinner.startIndex +'~'+ (tagListinner.startIndex+looping-1) +'，共有 '+ tagPostNum +' 篇文章';

			var footerButton = '<br>';
			if (tagListinner.startIndex == 1)
			{
				if (tagListSetting.postShow > tagPostNum  ) // recent comment may have same problem
				footerButton+= '</div>';
				else
				footerButton+= '<a href="javascript:tagListFunction.nextPage(1,tagListSetting.defaultPost);">下一頁</a></div>';
			}
			else if (tagListinner.startIndex+tagListSetting.postShow > tagPostNum)
			{
				footerButton+= '<a href="javascript:tagListFunction.nextPage(-1,tagListSetting.defaultPost);">上一頁</a></div>';
			}
			else 
			{
				footerButton += '<a href="javascript:tagListFunction.nextPage(-1,tagListSetting.defaultPost);">上一頁</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:tagListFunction.nextPage(1,tagListSetting.defaultPost);">下一頁</a></div>';
			}
			jQuery('#postsList').after(listInfo + footerButton);
		};
		addFooterButton();
	}
	else
	{
		//如果有人耍寶，就會跑出下面那段話
		jQuery('#postsList').html('一篇文章也沒有耶！<br>會不會是輸入錯誤的標籤啊？');
	}
};
tagListFunction.Run = function(tag)
{
//Shit， Google 會把中文的特殊字元轉成UTF-8，我還得自己轉回去
//http://wwwrsphysse.anu.edu.au/~mxk121/javascript/
	function dec2hex(dec) 
	{
		var h = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
		var hex = '';
		hex += h[Math.floor(dec / 0x1000)]; dec = dec % 0x1000;
		hex += h[Math.floor(dec / 0x100)]; dec = dec % 0x100;
		hex += h[Math.floor(dec / 0x10)]; dec = dec % 0x10;
		hex += h[Math.floor(dec / 0x1)]; dec = dec % 0x1;
		return hex;
	};
//http://wwwrsphysse.anu.edu.au/~mxk121/javascript/
// 這是個很有趣的寫法，我嘗試改變它的變數，但卻失敗了，敗的不明不白
	function html_unic(str) {
		var nc = '';
		var arr,s,c;
		for (var i = 0; i < str.length; i++) 
		{
			s = str.substr(i, 8);
			if (arr = s.match(/^&#[0-9]+;/)) //最神奇的是這裡，arr 變成了數字，之後居然還可以用 arr[0] 當成字串用，誇張的是，這樣轉出來的還是數字。
			{
				c = arr[0].replace(/[&#;]/g, '');
				c = dec2hex(c);
				c = "%u" + c;
				c = c.replace(/^%u00/, "%");
				i += arr[0].length - 1;
			} 
			else 
				c = str.charAt(i);
		nc += c;
		}
	return unescape(nc); // 直接丟 text 回去
};
	tag = html_unic(tag); // 幹，轉好久終於轉好了，這下可以用了吧。
	var encodeTag = encodeURIComponent(tag);//才怪，如果不轉成 URI 用的 code，照樣掛
	var tagList_script = document.createElement('script');
	if (tag == '')
		var blogLink = 'http://'+ tagListinner.blogName +'/feeds/posts/summary';
	else
		var blogLink = 'http://'+ tagListinner.blogName +'/feeds/posts/summary/-/' + encodeTag;
	tagList_script.setAttribute('src',blogLink +'/?alt=json-in-script&start-index='+ tagListinner.startIndex +'&max-results='+ tagListSetting.postShow +'&orderby=published&callback=tagListFunction.Util');
	tagList_script.setAttribute('type', 'text/javascript');
	tagList_script.setAttribute('id', 'listScript');
	document.documentElement.firstChild.appendChild(tagList_script);
};
//----------- 換頁的子程式，我改寫過了，上下頁跟換標籤都是用這哦 ---------------
// 簡單的說，傳入值 direction 可以等於 -1,0,1，分別是倒退，不動，前進
tagListFunction.nextPage = function(direction, tag)
{
	jQuery('#listScript').remove();
	jQuery('#postsList').next().remove().end().after('<div id="listLoading">'+tagListSetting.loadingImage+'</div>');
	if (direction == 1)
		tagListinner.startIndex += tagListSetting.postShow;
	else if (direction == -1)
		tagListinner.startIndex -= tagListSetting.postShow;
	else 
	{
		tagListinner.startIndex = 1;
		tagListSetting.defaultPost = tag;
	}	
	tagListFunction.Run(tag);
};

tagListFunction.fetchcategory = function()
{
	var categoryList = jQuery('#'+tagListSetting.labelName);
	if (categoryList.find('.widget-item-control')!=null)
		categoryList.find('.widget-item-control').before('<div id="postsList"></div>');
	else
		categoryList.find('.widget-content').append('<div id="postsList"></div>');
	tagListinner.blogName = categoryList.find('li a:eq(0)').attr('href').replace(/http:\/\/(.+)\/search\/label.+$/,'$1');
	categoryList.find('li').each(function(index){
		var categoryName = jQuery(this).text().replace(/(.+)\s\(\d+\)\s*$/,'$1'); // 這是最容易出現錯誤的地方，很多的標籤格式都不同，這應該可以適合的格式
		jQuery('a',this).attr('href','javascript:if(tagListSetting.defaultPost!="'+ categoryName +'") tagListFunction.nextPage(0,"'+ categoryName +'");');
		});
	if (tagListSetting.headerButton)
		tagListFunction.addHeaderButton();
	tagListFunction.Run(tagListSetting.defaultPost);
};

// 最後當然是在 DOM ready 之後才執行囉
jQuery(document).ready(function()
{
	if (BloggerExtOptions == undefined)
	{
		if (tagListSetting.labelName!='')
			tagListSetting.labelName = 'Label1';
	}
	else
	{	
		if (tagListSetting.labelName =='')
			tagListSetting.labelName = BloggerExtOptions.labelcloud_widget_id;
	}
	if (document.getElementById(tagListSetting.labelName)!=null)
		tagListFunction.fetchcategory();
});